package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author mengwei
 * @date 2019/8/9
 * @desc
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    UserService userService;

    @RequestMapping("/loginSuccess")
    public String loginSuccess(){
        System.out.println("登录成功");
        return "redirect:http://localhost:83/pages/main.html";
    }

    @RequestMapping("/loginFail")
    public String loginFail(){
        System.out.println("登录失败");
        return "redirect:http://localhost:83/login.html?param=loginFail";
    }

    @ResponseBody
    @RequestMapping("/findUsername")
    public Result findUsername(){
        try {
            //获取安全框架的上下文对象（全局对象）（包含了用户信息）
            SecurityContext context = SecurityContextHolder.getContext();
            System.out.println(context);
            //获取认证对象中用户对象
            User user = (User) context.getAuthentication().getPrincipal();
            //获取用户名
            String username = user.getUsername();
            return new Result(true,MessageConst.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_USERNAME_FAIL);
        }
    }
}
